package filemanager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import core.Client;

public class FileOpening {

	/**
	 * Runs a Java program into another JVM
	 * @param programName the name of the program
	 * @param fileName the name of the file to open
	 * @param extenzion the extenzion of the file to open
	 */
	public static void runJavaFile(String programDir, String executingName, String filePath)
	{
		try {
			String mainDir = Client.getInstance().getConfigs().get("mainDir");
			
			ProcessBuilder pb = new ProcessBuilder( "java", "-jar", programDir + "/" + executingName, filePath);
			Process pr = pb.start();
			
			pr.waitFor() ;
			BufferedReader buf = new BufferedReader( new InputStreamReader( pr.getInputStream() ) ) ;

			String line = buf.readLine();
			while (line  != null)
			{
				System.out.println(line);
				line = buf.readLine();
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * Runs an executable program
	 * @param programName the name of the program
	 * @param fileName the name of the file to open
	 * @param extenzion the extenzion of the file to open
	 */
	public static void runFile(String programDir, String executingName, String filePath)
	{
		try {

			ProcessBuilder pb;
			
			if(programDir.isEmpty())
				pb = new ProcessBuilder(executingName, filePath);
			else
				pb = new ProcessBuilder(programDir + "/" + executingName, filePath);
			
			Process pr = pb.start();
			
			pr.waitFor() ;
			BufferedReader buf = new BufferedReader( new InputStreamReader( pr.getInputStream() ) ) ;

			String line = buf.readLine();
			while (line  != null)
			{
				System.out.println(line);
				line = buf.readLine();
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	public static void main(String[] args) {
		FileOpening.runFile("openproj", "lalala", "pod");
	}
	*/
}
